package com.sxp.dao;

import com.sxp.model.Food;
import com.sxp.util.DBUtil;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by lakmini on 10/13/14.
 */
public class FoodDaoImpl implements FoodDao {
    @Override
    public void addFood(Food food) {
        Connection conn=null;
        try{
            conn= DBUtil.getConnection();
            PreparedStatement preparedStatement=conn.prepareStatement("insert into food(id,name) values(?,?)");
            preparedStatement.setInt(1, food.getFoodId());
            preparedStatement.setString(2, food.getFoodName());

            preparedStatement.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            DBUtil.closeConnection(conn);
        }
    }

    @Override
    public List<Food> getFoodList() {
        Connection conn = null;
        List<Food> foods = new ArrayList<Food>();
        try {
            conn = DBUtil.getConnection();
            Statement stmt = conn.createStatement();
            ResultSet rSet = stmt.executeQuery("select * from food");
            while (rSet.next()) {
                Food food=new Food();
                food.setFoodId(rSet.getInt("id"));
               food.setFoodName(rSet.getString("name"));

                foods.add(food);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }finally{
            DBUtil.closeConnection(conn);
        }

        return foods;
    }

    @Override
    public void removeFood(int id) {
        Connection conn=null;
        try{
            conn=DBUtil.getConnection();
            PreparedStatement preparedStatement=conn.prepareStatement("delete from food where id=?");
            preparedStatement.setInt(1, id);

            preparedStatement.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            DBUtil.closeConnection(conn);
        }
    }
}
